"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { useAuth } from '@/contexts/auth-context'
import Link from "next/link"
import { ChevronLeft, ChevronRight, Clock, Info } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { useTranslation } from "@/lib/i18n"

const mockCompetitions = [
  {
    id: 1,
    title: { zh: "Kaggle House Prices", en: "Kaggle House Prices Competition" },
    platform: "Kaggle",
    startDate: "2024-01-25",
    endDate: "2024-01-30",
    color: "#20BEFF",
    prize: "$15,000",
    participants: 2847,
  },
  {
    id: 2,
    title: { zh: "天池智慧城市AI", en: "Tianchi Smart City AI Challenge" },
    platform: "天池",
    startDate: "2024-01-26",
    endDate: "2024-02-02",
    color: "#FF6A00",
    prize: "¥100,000",
    participants: 1523,
  },
  {
    id: 3,
    title: { zh: "Climate Hackathon", en: "Climate Change Hackathon" },
    platform: "Devpost",
    startDate: "2024-01-28",
    endDate: "2024-01-29",
    color: "#4A90E2",
    prize: "$25,000",
    participants: 892,
  },
  {
    id: 4,
    title: { zh: "Google AI Challenge", en: "Google AI Challenge 2024" },
    platform: "Google",
    startDate: "2024-01-29",
    endDate: "2024-02-05",
    color: "#4285F4",
    prize: "$50,000",
    participants: 3421,
  },
  {
    id: 5,
    title: { zh: "Microsoft Azure", en: "Microsoft Azure Hackathon" },
    platform: "Microsoft",
    startDate: "2024-01-30",
    endDate: "2024-01-31",
    color: "#00BCF2",
    prize: "$30,000",
    participants: 1876,
  },
  {
    id: 6,
    title: { zh: "OpenAI GPT-4", en: "OpenAI GPT-4 Innovation Contest" },
    platform: "OpenAI",
    startDate: "2024-02-01",
    endDate: "2024-02-08",
    color: "#10A37F",
    prize: "$40,000",
    participants: 2156,
  },
]

export default function CalendarPage() {
  const { user, isLoading } = useAuth()
  const [currentDate, setCurrentDate] = useState(new Date())
  const [selectedCompetition, setSelectedCompetition] = useState(null)
  const [hoveredDay, setHoveredDay] = useState(null)
  const [currentLang, setCurrentLang] = useState<"zh" | "en">("zh")
  const { t } = useTranslation(currentLang)

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="glass border-white/20 p-8 text-center max-w-md mx-auto rounded-lg">
          <h2 className="text-2xl font-bold text-white mb-4">请先登录</h2>
          <p className="text-white/70 mb-6">您需要登录才能访问竞赛日历</p>
          <Link href="/auth/login">
            <Button className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700">
              前往登录
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  const today = new Date()
  const currentMonth = currentDate.getMonth()
  const currentYear = currentDate.getFullYear()

  // 获取当月的天数和第一天是星期几
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate()
  const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay()

  // 生成日历天数数组
  const calendarDays = []
  for (let i = 0; i < firstDayOfMonth; i++) {
    calendarDays.push(null)
  }
  for (let day = 1; day <= daysInMonth; day++) {
    calendarDays.push(day)
  }

  const monthNames = {
    zh: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
    en: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ],
  }

  const weekDays = {
    zh: ["日", "一", "二", "三", "四", "五", "六"],
    en: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  }

  // 检查某天是否在7天内
  const isWithinSevenDays = (day) => {
    if (!day) return false
    const date = new Date(currentYear, currentMonth, day)
    const diffTime = date.getTime() - today.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays >= 0 && diffDays <= 7
  }

  // 获取某天的竞赛
  const getCompetitionsForDay = (day) => {
    if (!day) return []
    const date = new Date(currentYear, currentMonth, day)

    return mockCompetitions
      .filter((comp) => {
        const startDate = new Date(comp.startDate)
        const endDate = new Date(comp.endDate)
        return date >= startDate && date <= endDate
      })
      .sort((a, b) => {
        const durationA = new Date(a.endDate).getTime() - new Date(a.startDate).getTime()
        const durationB = new Date(b.endDate).getTime() - new Date(b.startDate).getTime()
        return durationB - durationA
      })
  }

  // 渲染比赛时间线 - 类似图片中的效果
  const renderCompetitionTimelines = () => {
    const timelines = []
    const CELL_WIDTH = 100 / 7 // 每个单元格占用的百分比宽度
    const CELL_HEIGHT = 120 // 每个单元格的高度（像素）
    const TIMELINE_HEIGHT = 4 // 时间线高度

    mockCompetitions.forEach((competition, compIndex) => {
      const startDate = new Date(competition.startDate)
      const endDate = new Date(competition.endDate)

      // 计算在当前月份的显示范围
      const monthStart = new Date(currentYear, currentMonth, 1)
      const monthEnd = new Date(currentYear, currentMonth + 1, 0)

      if (endDate < monthStart || startDate > monthEnd) return

      const effectiveStart = startDate < monthStart ? monthStart : startDate
      const effectiveEnd = endDate > monthEnd ? monthEnd : endDate

      const startDay = effectiveStart.getDate()
      const endDay = effectiveEnd.getDate()

      // 找到开始和结束在日历中的位置
      const startIndex = calendarDays.indexOf(startDay)
      const endIndex = calendarDays.indexOf(endDay)

      if (startIndex === -1 || endIndex === -1) return

      // 计算跨越的行和列
      const startRow = Math.floor(startIndex / 7)
      const endRow = Math.floor(endIndex / 7)
      const startCol = startIndex % 7
      const endCol = endIndex % 7

      // 为每一行创建时间线段
      for (let row = startRow; row <= endRow; row++) {
        const isFirstRow = row === startRow
        const isLastRow = row === endRow

        const segmentStartCol = isFirstRow ? startCol : 0
        const segmentEndCol = isLastRow ? endCol : 6

        const left = segmentStartCol * CELL_WIDTH
        const width = (segmentEndCol - segmentStartCol + 1) * CELL_WIDTH
        const top = row * CELL_HEIGHT + 80 + compIndex * 8 // 80px 为头部偏移，8px 为竞赛间距

        timelines.push(
          <div
            key={`${competition.id}-${row}`}
            className="absolute rounded-full cursor-pointer transition-all duration-300 hover:scale-y-150 hover:shadow-lg"
            style={{
              backgroundColor: competition.color,
              left: `${left}%`,
              width: `${width}%`,
              height: `${TIMELINE_HEIGHT}px`,
              top: `${top}px`,
              boxShadow: `0 0 8px ${competition.color}40`,
            }}
            onClick={() => setSelectedCompetition(competition)}
            title={competition.title[currentLang]}
          >
            {/* 添加渐变效果 */}
            <div
              className="absolute inset-0 rounded-full opacity-60"
              style={{
                background: `linear-gradient(90deg, ${competition.color}80, ${competition.color}, ${competition.color}80)`,
              }}
            />
          </div>,
        )
      }
    })

    return timelines
  }

  const navigateMonth = (direction) => {
    setCurrentDate((prev) => {
      const newDate = new Date(prev)
      newDate.setMonth(prev.getMonth() + direction)
      return newDate
    })
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="text-center mb-8">
          <h1 className="text-responsive-4xl font-bold mb-4 text-gradient-animate">{t("calendarTitle")}</h1>
          <p className="text-responsive-xl" style={{ color: "white" }}>
            {t("calendarSubtitle")}
          </p>

          {/* 语言切换 */}
          <div className="flex justify-center gap-2 mt-4">
            <Button
              variant={currentLang === "zh" ? "default" : "outline"}
              size="sm"
              onClick={() => setCurrentLang("zh")}
              className={
                currentLang === "zh" ? "bg-gradient-to-r from-purple-500 to-pink-500" : "bg-transparent border-gray-500"
              }
              style={{ color: "white" }}
            >
              中文
            </Button>
            <Button
              variant={currentLang === "en" ? "default" : "outline"}
              size="sm"
              onClick={() => setCurrentLang("en")}
              className={
                currentLang === "en" ? "bg-gradient-to-r from-purple-500 to-pink-500" : "bg-transparent border-gray-500"
              }
              style={{ color: "white" }}
            >
              English
            </Button>
          </div>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* 日历主体 */}
          <div className="lg:col-span-3">
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
              <Card className="glass border-0 card-hover">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <h2 className="text-2xl font-bold" style={{ color: "white" }}>
                      {currentYear} {monthNames[currentLang][currentMonth]}
                    </h2>
                    <div className="flex items-center gap-2">
                      <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => navigateMonth(-1)}
                          className="bg-transparent border-gray-500 hover:border-purple-400 hover:bg-gradient-to-r hover:from-purple-500 hover:to-pink-500"
                          style={{ color: "white" }}
                        >
                          <ChevronLeft className="w-4 h-4" />
                        </Button>
                      </motion.div>
                      <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Button
                          size="sm"
                          onClick={() => setCurrentDate(new Date())}
                          className="bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600"
                          style={{ color: "white" }}
                        >
                          {t("today")}
                        </Button>
                      </motion.div>
                      <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => navigateMonth(1)}
                          className="bg-transparent border-gray-500 hover:border-purple-400 hover:bg-gradient-to-r hover:from-purple-500 hover:to-pink-500"
                          style={{ color: "white" }}
                        >
                          <ChevronRight className="w-4 h-4" />
                        </Button>
                      </motion.div>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="relative">
                  {/* 星期标题 */}
                  <div className="grid grid-cols-7 gap-2 mb-4">
                    {weekDays[currentLang].map((day) => (
                      <div key={day} className="text-center text-sm font-medium py-2" style={{ color: "white" }}>
                        {day}
                      </div>
                    ))}
                  </div>

                  {/* 日历网格容器 */}
                  <div className="relative">
                    {/* 日历网格 */}
                    <div className="grid grid-cols-7 gap-2 relative" style={{ minHeight: "600px" }}>
                      {calendarDays.map((day, index) => {
                        const competitions = getCompetitionsForDay(day)
                        const isHighlighted = isWithinSevenDays(day)
                        const isToday =
                          day && new Date(currentYear, currentMonth, day).toDateString() === today.toDateString()

                        return (
                          <motion.div
                            key={index}
                            initial={{ opacity: 0, scale: 0.8 }}
                            animate={{ opacity: 1, scale: 1 }}
                            transition={{ delay: 0.4 + index * 0.01 }}
                            whileHover={{ scale: 1.02 }}
                            className={`calendar-day ${isHighlighted ? "highlighted" : ""} ${isToday ? "today" : ""}`}
                            style={{ height: "120px" }}
                            onMouseEnter={() => setHoveredDay(day)}
                            onMouseLeave={() => setHoveredDay(null)}
                          >
                            {day && (
                              <>
                                <div
                                  className={`text-sm font-medium mb-2 ${isToday ? "text-blue-400" : ""}`}
                                  style={{ color: isToday ? "#60a5fa" : "white" }}
                                >
                                  {day}
                                </div>

                                {/* 竞赛数量指示 */}
                                {competitions.length > 0 && (
                                  <div className="absolute bottom-2 right-2">
                                    <div className="w-5 h-5 bg-purple-500 rounded-full flex items-center justify-center text-xs font-bold text-white">
                                      {competitions.length}
                                    </div>
                                  </div>
                                )}

                                {/* 悬浮信息 */}
                                {hoveredDay === day && competitions.length > 0 && (
                                  <motion.div
                                    initial={{ opacity: 0, y: 10 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    className="absolute z-30 mt-2 p-3 glass-light rounded-lg shadow-xl border border-white/20 min-w-[200px]"
                                    style={{ top: "100%", left: "0" }}
                                  >
                                    <div className="text-xs space-y-2">
                                      {competitions.slice(0, 3).map((comp) => (
                                        <div key={comp.id} className="flex items-center gap-2">
                                          <div
                                            className="w-3 h-3 rounded-full"
                                            style={{ backgroundColor: comp.color }}
                                          />
                                          <div>
                                            <div className="font-medium" style={{ color: "white" }}>
                                              {comp.title[currentLang]}
                                            </div>
                                            <div style={{ color: "#d1d5db" }}>
                                              {comp.platform} • {comp.prize}
                                            </div>
                                          </div>
                                        </div>
                                      ))}
                                      {competitions.length > 3 && (
                                        <div style={{ color: "#9ca3af" }}>
                                          +{competitions.length - 3}{" "}
                                          {currentLang === "zh" ? "更多竞赛" : "more competitions"}
                                        </div>
                                      )}
                                    </div>
                                  </motion.div>
                                )}
                              </>
                            )}
                          </motion.div>
                        )
                      })}
                    </div>

                    {/* 渲染跨日期的比赛时间线 */}
                    <div className="absolute inset-0 pointer-events-none">
                      <div className="relative w-full h-full">{renderCompetitionTimelines()}</div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 侧边栏 */}
          <div className="lg:col-span-1">
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
              className="space-y-6"
            >
              {/* 图例 */}
              <Card className="glass border-0 card-hover">
                <CardHeader>
                  <CardTitle className="text-lg" style={{ color: "white" }}>
                    {t("platformLegend")}
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  {[
                    { name: "Kaggle", color: "#20BEFF" },
                    { name: "天池", color: "#FF6A00" },
                    { name: "Devpost", color: "#4A90E2" },
                    { name: "Google", color: "#4285F4" },
                    { name: "Microsoft", color: "#00BCF2" },
                    { name: "OpenAI", color: "#10A37F" },
                  ].map((platform, index) => (
                    <motion.div
                      key={platform.name}
                      initial={{ opacity: 0, x: 20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: 0.6 + index * 0.1 }}
                      className="flex items-center gap-3"
                    >
                      <div className="w-4 h-1 rounded-full" style={{ backgroundColor: platform.color }} />
                      <span className="text-sm" style={{ color: "white" }}>
                        {platform.name}
                      </span>
                    </motion.div>
                  ))}
                </CardContent>
              </Card>

              {/* 即将开始的竞赛 */}
              <Card className="glass border-0 card-hover">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2" style={{ color: "white" }}>
                    <Clock className="w-5 h-5 text-orange-400" />
                    {t("upcomingCompetitions")}
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  {mockCompetitions.slice(0, 3).map((comp, index) => (
                    <motion.div
                      key={comp.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.8 + index * 0.1 }}
                      whileHover={{ scale: 1.02 }}
                      className="p-3 rounded-lg bg-white/10 cursor-pointer hover:bg-white/20 transition-all duration-300"
                      onClick={() => setSelectedCompetition(comp)}
                    >
                      <h4 className="font-medium text-sm mb-1" style={{ color: "white" }}>
                        {comp.title[currentLang]}
                      </h4>
                      <div className="flex items-center justify-between text-xs" style={{ color: "#d1d5db" }}>
                        <span>{comp.platform}</span>
                        <span>{comp.startDate}</span>
                      </div>
                    </motion.div>
                  ))}
                </CardContent>
              </Card>

              {/* 选中的竞赛详情 */}
              {selectedCompetition && (
                <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
                  <Card className="glass border-0 card-hover">
                    <CardHeader>
                      <CardTitle className="text-lg flex items-center gap-2" style={{ color: "white" }}>
                        <Info className="w-5 h-5 text-blue-400" />
                        {t("competitionDetails")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <h4 className="font-medium" style={{ color: "white" }}>
                        {selectedCompetition.title[currentLang]}
                      </h4>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between">
                          <span style={{ color: "#d1d5db" }}>{t("platform")}</span>
                          <span style={{ color: "white" }}>{selectedCompetition.platform}</span>
                        </div>
                        <div className="flex justify-between">
                          <span style={{ color: "#d1d5db" }}>{currentLang === "zh" ? "奖金" : "Prize"}</span>
                          <span className="text-green-400 font-medium">{selectedCompetition.prize}</span>
                        </div>
                        <div className="flex justify-between">
                          <span style={{ color: "#d1d5db" }}>{t("participants")}</span>
                          <span style={{ color: "white" }}>{selectedCompetition.participants.toLocaleString()}</span>
                        </div>
                        <div className="flex justify-between">
                          <span style={{ color: "#d1d5db" }}>{t("startDate")}</span>
                          <span style={{ color: "white" }}>{selectedCompetition.startDate}</span>
                        </div>
                        <div className="flex justify-between">
                          <span style={{ color: "#d1d5db" }}>{t("endDate")}</span>
                          <span style={{ color: "white" }}>{selectedCompetition.endDate}</span>
                        </div>
                      </div>
                      <div className="flex gap-2 pt-2">
                        <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} className="flex-1">
                          <Button
                            size="sm"
                            className="w-full bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                            style={{ color: "white" }}
                          >
                            {t("viewDetails")}
                          </Button>
                        </motion.div>
                        <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                          <Button
                            size="sm"
                            className="bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600"
                            style={{ color: "white" }}
                          >
                            {t("joinTeam")}
                          </Button>
                        </motion.div>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              )}
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}
